package com.learn.egweibo2.base.exception;

import com.learn.egweibo2.base.response.JsonResult;
import com.learn.egweibo2.base.response.StatusCode;
import jdk.net.SocketFlow;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandlerException(IllegalArgumentException ex) {
        log.error("IllegalArgumentException:{}", ex.getMessage());
        return new JsonResult(StatusCode.OPERATION_FAILED,ex.getMessage());
    }

    @ExceptionHandler
    public JsonResult doHandler(MethodArgumentNotValidException ex){
        String data = ex.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException:{}", data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }

    @ExceptionHandler
    public JsonResult doHandlerConstraintException(ConstraintViolationException ex) {
        String data = ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException:{}", data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }

    @ExceptionHandler
    public JsonResult doHandlerException(RuntimeException ex) {
        log.error("RuntimeException:{}", ex.getMessage());
        return new JsonResult(StatusCode.OPERATION_FAILED,ex.getMessage());
    }

    @ExceptionHandler
    public JsonResult doHandlerException(Throwable ex) {
        log.error("Throwable:{}", ex.getMessage());
        return new JsonResult(StatusCode.OPERATION_FAILED,ex.getMessage());
    }
}
